<template>
  <view class="container">
    <view class="hero-card">
      <view class="hero-title">便民服务</view>
      <view class="hero-desc">村务办事，从这里开始</view>
    </view>

    <view class="service-section" v-if="activeServices.length > 0">
      <view
        class="service-card"
        v-for="service in activeServices"
        :key="service.key"
        @click="handleServiceTap(service)"
      >
        <view class="service-icon">{{ service.icon }}</view>
        <view class="service-info">
          <text class="service-title">{{ service.title }}</text>
          <text class="service-desc">{{ service.description }}</text>
        </view>
        <view class="service-arrow">></view>
      </view>
    </view>

    <view class="empty-state" v-else>
      <text class="empty-title">暂无可用的便民服务</text>
      <text class="empty-desc">请联系管理员在后台开启需要的功能</text>
    </view>

    <view class="tips-card">
      <view class="tips-title">提示</view>
      <view class="tips-item">· 如需新增服务，请联系系统管理员</view>
    </view>
  </view>
</template>

<script>
import authService from '@/utils/auth.js'
import { convenienceApi } from '@/utils/api-simple.js'

export default {
  data() {
    return {
      loading: false,
      serviceMap: {},
      defaultServices: {
        demandCollection: {
          key: 'demandCollection',
          title: '需求收集',
          description: '提交民生诉求与建议',
          icon: '📝',
          enabled: true,
          actionType: 'navigate',
          target: '/pages/demand-collection/demand-collection'
        },
        expressService: {
          key: 'expressService',
          title: '快递服务',
          description: '快递代收、物流查询',
          icon: '📦',
          enabled: true,
          actionType: 'navigate',
          target: '/pages/express-service/express-service'
        },
        publicFeedback: {
          key: 'publicFeedback',
          title: '民意收集',
          description: '查看反馈处理进度',
          icon: '📋',
          enabled: true,
          actionType: 'navigate',
          target: '/pages/feedback/feedback'
        }
      }
    }
  },

  computed: {
    activeServices() {
      return Object.values(this.serviceMap).filter(item => item.enabled)
    }
  },

  onLoad() {
    this.loadServiceConfig()
  },

  onShow() {
    this.loadServiceConfig()
  },

  onPullDownRefresh() {
    this.loadServiceConfig()
  },

  methods: {
    mergeServices(remoteData) {
      const merged = { ...this.defaultServices }
      if (Array.isArray(remoteData)) {
        remoteData.forEach(item => {
          if (item && item.key && merged[item.key]) {
            merged[item.key] = { ...merged[item.key], ...item }
          }
        })
      } else if (remoteData && typeof remoteData === 'object') {
        Object.keys(remoteData).forEach(key => {
          if (merged[key]) {
            merged[key] = { ...merged[key], ...remoteData[key] }
          }
        })
      }
      return merged
    },

    async loadServiceConfig() {
      this.loading = true
      try {
        const response = await convenienceApi.getServiceConfig()
        if (response?.code === 200 && response.data) {
          this.serviceMap = this.mergeServices(response.data)
        } else {
          this.serviceMap = { ...this.defaultServices }
        }
      } catch (error) {
        console.warn('获取便民服务配置失败，使用默认值', error)
        this.serviceMap = { ...this.defaultServices }
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    handleServiceTap(service) {
      const authRequiredKeys = ['demandCollection', 'expressService']
      if (authRequiredKeys.includes(service.key) && !authService.isLoggedIn()) {
        uni.redirectTo({
          url: '/pages/login/login?from=/pages/convenience/convenience'
        })
        return
      }

      if (!service.enabled) {
        uni.showToast({
          title: '该服务已关闭',
          icon: 'none'
        })
        return
      }

      switch (service.actionType) {
        case 'tab':
          uni.switchTab({
            url: service.target || '/pages/village-intro/village-intro'
          })
          break
        case 'navigate':
          if (service.target) {
            uni.navigateTo({ url: service.target })
          } else {
            this.showMissingConfig()
          }
          break
        case 'webview':
          if (service.target) {
            this.openWebLink(service.target)
          } else {
            this.showMissingConfig()
          }
          break
        case 'modal':
          uni.showModal({
            title: service.title,
            content: service.message || '该服务由后台配置，当前暂无内容。',
            showCancel: false
          })
          break
        default:
          this.showMissingConfig()
          break
      }
    },

    openWebLink(url) {
      if (!url) {
        this.showMissingConfig()
        return
      }
      uni.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
      })
    },

    showMissingConfig() {
      uni.showToast({
        title: '配置缺失，请联系管理员',
        icon: 'none'
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 24rpx;
  min-height: 100vh;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.hero-card {
  background: linear-gradient(135deg, #4caf50, #45a049);
  border-radius: 24rpx;
  padding: 40rpx 32rpx;
  color: #fff;
  margin-bottom: 30rpx;
  box-shadow: 0 20rpx 40rpx rgba(76, 175, 80, 0.25);
}

.hero-title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.hero-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

.service-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.service-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 28rpx 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.06);
}

.service-card:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.service-icon {
  font-size: 48rpx;
  margin-right: 24rpx;
}

.service-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.service-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.service-desc {
  font-size: 26rpx;
  color: #888;
  margin-top: 6rpx;
}

.service-arrow {
  font-size: 32rpx;
  color: #ccc;
}

.empty-state {
  margin-top: 120rpx;
  text-align: center;
  color: #999;
}

.empty-title {
  font-size: 30rpx;
  font-weight: bold;
}

.empty-desc {
  font-size: 26rpx;
  margin-top: 16rpx;
  display: block;
}

.tips-card {
  margin-top: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 28rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.tips-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.tips-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}
</style>

